package com.nari.ncps.screen.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.dryport.DryportProdoperPortGather;
import com.nari.ncps.screen.mapper.dryport.DryportProdoperPortGatherMapper;
import com.nari.ncps.screen.service.dryport.DryportProdoperPortGatherService;
import com.nari.ncps.screen.vo.dryport.PortGatherVO;
import com.nari.ncps.screen.vo.wholeproduct.PortGatheringVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 集港量情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class DryportProdoperPortGatherServiceImpl extends ServiceImpl<DryportProdoperPortGatherMapper, DryportProdoperPortGather> implements DryportProdoperPortGatherService {

    @Autowired
    private DryportProdoperPortGatherMapper dryportProdoperPortGatherMapper;

    @Override
    public List<PortGatherVO> getMonthlyStatsByYear(Integer year) {
        // 从数据库查询数据
        List<DryportProdoperPortGather> entityList = baseMapper.getMonthlyStatsByYear(year);
        
        // 转换为VO对象
        return entityList.stream().map(entity -> {
            PortGatherVO vo = new PortGatherVO();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<PortGatheringVO> getAnnualPortGathering() {
        // 从数据库查询年度汇总数据
        List<DryportProdoperPortGather> annualStatsList = baseMapper.getAnnualStats();
        
        // 构建结果列表
        List<PortGatheringVO> resultList = new ArrayList<>();
        for(DryportProdoperPortGather data:annualStatsList){
            PortGatheringVO vo=new PortGatheringVO();
            vo.setYear(data.getYear());
            vo.setGatheringPlanned(data.getGatheringPlanned());
            vo.setGatheringCompleted(data.getGatheringCompleted());
            vo.setYoyRate(data.getCompletionRate());
            resultList.add(vo);
        }
//        // 遍历查询结果，计算同比率
//        for (int i = 0; i < annualStatsList.size(); i++) {
//            DryportProdoperPortGather current = annualStatsList.get(i);
//            PortGatheringVO vo = new PortGatheringVO();
//
//            vo.setYear(current.getYear());
//            vo.setGatheringPlanned(current.getGatheringPlanned());
//            vo.setGatheringCompleted(current.getGatheringCompleted());
//
//            // 计算同比率：(当年完成量 - 去年完成量) / 去年完成量 * 100
//            // 注意：i+1 是因为数据是按年份降序排列的
//            if (i + 1 < annualStatsList.size()) {
//                DryportProdoperPortGather previous = annualStatsList.get(i + 1);
//                BigDecimal currentCompleted = current.getGatheringCompleted();
//                BigDecimal previousCompleted = previous.getGatheringCompleted();
//
//                if (previousCompleted != null && previousCompleted.compareTo(BigDecimal.ZERO) != 0) {
//                    BigDecimal yoyRate = currentCompleted.subtract(previousCompleted)
//                            .divide(previousCompleted, 4, RoundingMode.HALF_UP)
//                            .multiply(new BigDecimal("100"))
//                            .setScale(2, RoundingMode.HALF_UP);
//                    vo.setYoyRate(yoyRate);
//                } else {
//                    vo.setYoyRate(BigDecimal.ZERO);
//                }
//            } else {
//                // 第一年没有同比数据
//                vo.setYoyRate(BigDecimal.ZERO);
//            }
//
//            resultList.add(vo);
//        }
        
        return resultList;
    }

    @Override
    public List<PortGatherVO> getLatest12MonthsStats() {
        // 计算近12个月的年月范围
        // 获取当前日期和前12个月的日期
        LocalDate now = LocalDate.now();
        LocalDate twelveMonthsAgo = now.minusMonths(11); // 包含当前月，共12个月

        // 格式化日期为 statistic_time 格式 (yyyyMM)
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        String startMonth = twelveMonthsAgo.format(formatter);
        String endMonth = now.format(formatter);

        // 构建查询条件
        LambdaQueryWrapper<DryportProdoperPortGather> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DryportProdoperPortGather::getOrgCode, "100360")
                .eq(DryportProdoperPortGather::getDateType, 1) // 月数据
                .between(DryportProdoperPortGather::getStatisticTime, startMonth, endMonth)
                .orderByAsc(DryportProdoperPortGather::getStatisticTime);

        // 执行查询
        List<DryportProdoperPortGather> entityList =  dryportProdoperPortGatherMapper.selectList(lqw);

        // 转换为 VO
        List<PortGatherVO> voList = entityList.stream().map(entity -> {
            PortGatherVO vo = new PortGatherVO();
            vo.setYear(entity.getYear());
            vo.setMonth(entity.getMonth());

            // 将 statistic_time 转换为 yyyy-MM 格式
            if (entity.getStatisticTime() != null && entity.getStatisticTime().length() == 6) {
                String dateStr = entity.getStatisticTime();
                vo.setDate(dateStr.substring(0, 4) + "-" + dateStr.substring(4, 6));
            }

            vo.setGatheringPlanned(entity.getGatheringPlanned());
            vo.setGatheringCompleted(entity.getGatheringCompleted());
            return vo;
        }).collect(Collectors.toList());

        List<PortGatherVO> sortedList = voList.stream()
                .sorted(Comparator.comparing(PortGatherVO::getYear)
                        .thenComparing(PortGatherVO::getMonth))
                .collect(Collectors.toList());
        return sortedList;
    }

}
